<template>
  <div class="transaction-history-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>交易记录查询</h1>
      <p>查看您的所有交易历史，支持按时间和类型筛选</p>
    </div>

    <!-- 交易统计卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="8">
        <el-card class="stat-card" shadow="never">
          <div class="stat-header">
            <div class="stat-title">本月交易</div>
            <el-icon class="stat-icon"><ArrowUp /></el-icon>
          </div>
          <div class="stat-value">{{ formattedTotalTransactions }}</div>
          <div class="stat-subtitle">笔数</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card" shadow="never">
          <div class="stat-header">
            <div class="stat-title">收入总额</div>
            <el-icon class="stat-icon"><Plus /></el-icon>
          </div>
          <div class="stat-value">{{ formattedIncome }}</div>
          <div class="stat-subtitle">¥</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card" shadow="never">
          <div class="stat-header">
            <div class="stat-title">支出总额</div>
            <el-icon class="stat-icon"><Minus /></el-icon>
          </div>
          <div class="stat-value">{{ formattedExpense }}</div>
          <div class="stat-subtitle">¥</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-card class="filter-card" shadow="never">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="交易类型">
              <el-select v-model="filter.type" placeholder="请选择交易类型">
                <el-option label="全部" value="" />
                <el-option label="收入" value="收入" />
                <el-option label="支出" value="支出" />
                <el-option label="转账" value="转账" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="时间范围">
              <el-date-picker
                  v-model="filter.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :disabled-date="disabledDate"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="金额范围">
              <el-input-number
                  v-model="filter.amountMin"
                  :min="0"
                  placeholder="最小金额"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label=" ">
              <el-input-number
                  v-model="filter.amountMax"
                  :min="0"
                  placeholder="最大金额"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: right; padding: 0 10px">
            <el-button @click="resetFilter">重置</el-button>
          </el-col>
          <el-col :span="2" style="text-align: right; padding: 0 10px">
            <el-button type="primary" @click="applyFilter">筛选</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 交易记录表格 -->
    <el-card class="transaction-table-card" shadow="never">
      <div class="table-header">
        <div class="table-title">交易记录列表</div>
        <el-button type="primary" @click="exportRecords">
          <el-icon><Download /></el-icon>导出记录
        </el-button>
      </div>
      <el-table
          :data="filteredTransactions"
          stripe
          style="width: 100%"
          @sort-change="handleSortChange"
          height="400"
      >
        <el-table-column prop="tradeDate" label="日期" width="180" sortable />
        <el-table-column prop="tradeType" label="交易类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.tradeType)">{{
                row.tradeType
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tradeMoney" label="金额" width="120" sortable>
          <template #default="{ row }">
            <span
                :class="row.tradeType === '收入' ? 'positive-amount' : 'negative-amount'">
              {{ row.tradeType === "收入" ? "+" : "-" }}{{ row.tradeMoney }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="cardID" label="交易卡号" width="200" />
        <el-table-column prop="remark" label="交易描述" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from "vue";
import {
  ArrowUp,
  Plus,
  Minus,
  Download
} from "@element-plus/icons-vue";
import numeral from "numeral";
import axios from "axios";

export default {
  name: "TransactionHistoryView",
  components: {
    ArrowUp,
    Plus,
    Minus,
    Download,
  },
  setup() {
    // 获取当前登录的用户名
    const username = ref(localStorage.getItem("username") || "");

    // 卡片列表
    const cards = ref([]);

    // 交易记录数据
    const transactions = ref([]);

    // 筛选条件
    const filter = ref({
      type: "",
      dateRange: [],
      amountMin: 0,
      amountMax: 0,
    });

    // 分页数据
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    // 计算属性：筛选后的交易记录
    const filteredTransactions = computed(() => {
      let result = [...transactions.value];

      // 按类型筛选
      if (filter.value.type) {
        result = result.filter((item) => item.tradeType === filter.value.type);
      }

      // 按日期范围筛选
      if (filter.value.dateRange.length === 2) {
        const [startDate, endDate] = filter.value.dateRange;
        result = result.filter((item) => {
          const transactionDate = new Date(item.tradeDate);
          return transactionDate >= startDate && transactionDate <= endDate;
        });
      }

      // 按金额范围筛选
      if (filter.value.amountMin > 0) {
        result = result.filter(
            (item) => parseFloat(item.tradeMoney) >= filter.value.amountMin
        );
      }
      if (filter.value.amountMax > 0) {
        result = result.filter(
            (item) => parseFloat(item.tradeMoney) <= filter.value.amountMax
        );
      }

      return result;
    });

    // 计算统计数据
    const formattedTotalTransactions = computed(
        () => filteredTransactions.value.length
    );
    const income = computed(() => {
      return filteredTransactions.value
          .filter((item) => item.tradeType === "收入")
          .reduce((sum, item) => sum + parseFloat(item.tradeMoney), 0);
    });
    const expense = computed(() => {
      return filteredTransactions.value
          .filter((item) => item.tradeType === "支出")
          .reduce((sum, item) => sum + parseFloat(item.tradeMoney), 0);
    });
    const formattedIncome = computed(() =>
        numeral(income.value).format("0,0.00")
    );
    const formattedExpense = computed(() =>
        numeral(expense.value).format("0,0.00")
    );

    // 禁用过去日期
    const disabledDate = (time) => {
      return time.getTime() > Date.now();
    };

    // 处理排序
    const handleSortChange = (sort) => {
      if (!sort.prop) return;

      const newTransactions = [...transactions.value];
      newTransactions.sort((a, b) => {
        if (sort.order === "ascending") {
          return a[sort.prop] > b[sort.prop] ? 1 : -1;
        } else {
          return a[sort.prop] < b[sort.prop] ? 1 : -1;
        }
      });

      transactions.value = newTransactions;
    };

    // 应用筛选
    const applyFilter = () => {
      total.value = filteredTransactions.value.length;
    };

    // 重置筛选
    const resetFilter = () => {
      filter.value = {
        type: "",
        dateRange: [],
        amountMin: 0,
        amountMax: 0,
      };
      applyFilter();
    };

    // 导出记录
    const exportRecords = () => {
      console.log("导出交易记录");
      // 这里可以添加导出逻辑
    };

    // 获取类型对应的颜色
    const getTypeColor = (type) => {
      switch (type) {
        case "收入":
          return "success";
        case "支出":
          return "danger";
        case "转账":
          return "info";
        default:
          return "";
      }
    };

    // 从后端获取用户卡片信息
    const fetchCards = async () => {
      try {
        if (!username.value) {
          console.error("获取用户名失败，请重新登录");
          return;
        }
        const response = await axios.get(
            `http://localhost:8088/api/cards/user?username=${username.value}`
        );
        cards.value = response.data;
      } catch (error) {
        console.error("获取卡片信息失败:", error);
      }
    };

    // 根据卡号获取交易记录
    const fetchTransactionsByCardID = async (cardID) => {
      try {
        const response = await axios.get(
            `http://localhost:8088/api/transactions/select1/${cardID}`
        );
        return response.data;
      } catch (error) {
        console.error(`获取卡号 ${cardID} 的交易记录失败:`, error);
        return [];
      }
    };

    // 获取所有卡片的交易记录
    const fetchAllCardsTransactions = async () => {
      try {
        await fetchCards();
        if (cards.value.length === 0) {
          console.log("没有找到卡片信息");
          return;
        }
        const transactionPromises = cards.value.map(card => {
          if (!card.cardID) return Promise.resolve([]); // 跳过 cardID 为空的卡片
          return fetchTransactionsByCardID(card.cardID);
        });
        const transactionResults = await Promise.all(transactionPromises);
        // 合并所有交易记录，并过滤掉空记录
        transactions.value = transactionResults
            .flat()
            .filter(record => record !== null && record !== undefined && record.tradeMoney !== null && record.tradeMoney !== undefined);
        total.value = transactions.value.length;
      } catch (error) {
        console.error("获取所有卡片的交易记录失败:", error);
      }
    };

    onMounted(() => {
      fetchAllCardsTransactions();
    });

    return {
      username,
      cards,
      transactions,
      filter,
      currentPage,
      pageSize,
      total,
      filteredTransactions,
      formattedTotalTransactions,
      income,
      expense,
      formattedIncome,
      formattedExpense,
      disabledDate,
      handleSortChange,
      applyFilter,
      resetFilter,
      exportRecords,
      getTypeColor,
    };
  },
};
</script>

<style scoped>
.transaction-history-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #999;
}

.statistics-row {
  margin-bottom: 20px;
}

.stat-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.stat-header {
  display: flex;
  align-items: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-right: 10px;
}

.stat-icon {
  font-size: 16px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
}

.stat-subtitle {
  font-size: 14px;
  color: #909399;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
}

.transaction-table-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
}

.positive-amount {
  color: #67c23a;
  font-weight: 500;
}

.negative-amount {
  color: #f56c6c;
  font-weight: 500;
}
</style>